package com.zyzd.general.module.recyclerview.edit;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.zyzd.general.R;
import com.zyzd.general.entity.local.UserEntity;
import com.zyzd.general.utils.TextWatcherAdapter;
import com.zyzd.retrofit.base.BaseAdapter;

import butterknife.BindView;
import butterknife.ButterKnife;

public class EditRecyclerAdapter extends BaseAdapter<EditRecyclerAdapter.EditRecyclerHolder, UserEntity> {
    public EditRecyclerAdapter(Context context) {
        super(context);
    }

    @Override
    protected void onBindHolder(@NonNull final EditRecyclerHolder holder, int position) {
        final UserEntity item = getItem(position);

        holder.setIsRecyclable(false);
        holder.etName.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                item.setUser_name(holder.etName.getText().toString());
            }
        });
        holder.etAge.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String ageStr = holder.etAge.getText().toString();
                item.setAge(TextUtils.isEmpty(ageStr) ? 0 : Integer.valueOf(ageStr.toString()));
            }
        });

        holder.etName.setText(item.getUserName());
        holder.etAge.setText(String.valueOf(item.getAge()));
    }

    @NonNull
    @Override
    public EditRecyclerHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new EditRecyclerHolder(mInflater.inflate(R.layout.item_recycler_edit, parent, false));
    }

    static class EditRecyclerHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.et_name)
        EditText etName;
        @BindView(R.id.et_age)
        EditText etAge;

        EditRecyclerHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
